package com.dabaozhan.modules.wx_app.facade.impl;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dabaozhan.common.exception.RRException;
import com.dabaozhan.modules.wx_app.base.PageResult;
import com.dabaozhan.modules.wx_app.dao.RiskMapper;
import com.dabaozhan.modules.wx_app.entity.InventoryEntity;
import com.dabaozhan.modules.wx_app.entity.QueryListBaseEntity;
import com.dabaozhan.modules.wx_app.entity.RiskEntity;
import com.dabaozhan.modules.wx_app.enums.ResponseCodeEnum;
import com.dabaozhan.modules.wx_app.facade.InventoryFacade;
import com.dabaozhan.modules.wx_app.service.InventoryService;

@Service("inventoryFacade")
public class InventoryFacadeImpl implements InventoryFacade{

	@Autowired
	private InventoryService inventoryService;
	@Autowired
	private RiskMapper riskMapper;
	
	@Override
	public PageResult<List<InventoryEntity>> getInventoryList(QueryListBaseEntity entity) {
		long totalCount = inventoryService.getInventoryCount(entity);
		if(totalCount <=0){
			throw new RRException(ResponseCodeEnum.ResponseCode_400.getCode(),ResponseCodeEnum.ResponseCode_400.getDescription());
		}
		//查询开始区间
		int beginIndex = (entity.getPage()-1)*entity.getSize();
		entity.setBeginIndex(beginIndex);
		//查询结束区间
		int endIndex = entity.getPage()*entity.getSize();
		entity.setEndIndex(endIndex);
		List<InventoryEntity> list =inventoryService.getInventoryList(entity);
		for(InventoryEntity invEntity:list){
			RiskEntity riskEntity = riskMapper.getRiskWaring(invEntity.getUserId(), invEntity.getParentId(), invEntity.getCategoryId());
			if(null == riskEntity){
				invEntity.setWarning(new BigDecimal("-1"));
				invEntity.setRiskStatus(1);
			}else{
				invEntity.setWarning(riskEntity.getWarning());
				if(invEntity.getTotalWeight().compareTo(riskEntity.getWarning())>0){
					invEntity.setRiskStatus(2);
				}else{
					invEntity.setRiskStatus(1);
				}
			}
		}
		PageResult<List<InventoryEntity>> pageResult = new PageResult<List<InventoryEntity>>();
		pageResult.setListData(list);
		pageResult.setTotal(totalCount);
		return pageResult;
	}

	@Override
	public int addInventory(InventoryEntity entity) {
		int result = inventoryService.addInventory(entity);
		if(result <=0){
			throw new RRException(ResponseCodeEnum.ResponseCode_102.getCode(),ResponseCodeEnum.ResponseCode_102.getDescription());
		}
		return result;
	}

	@Override
	public int deleteInventory(InventoryEntity entity) {
		if(StringUtils.isBlank(entity.getId())){
			throw new RRException(ResponseCodeEnum.ResponseCode_101.getCode(),"id不能为空");
		}
		int result = inventoryService.deleteInventory(entity);
		if(result <=0){
			throw new RRException(ResponseCodeEnum.ResponseCode_106.getCode(),ResponseCodeEnum.ResponseCode_106.getDescription());
		}
		return result;
	}

}
